package linc.cool.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yqlin
 * @date 2021/12/28 12:34 AM
 * @description
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class StockController {
    private final StringRedisTemplate stringRedisTemplate;
    private final ReentrantLock reentrantLock = new ReentrantLock();

    @RequestMapping("/reduce_stock")
    public String reduceStock() {
        String stockValue = stringRedisTemplate.opsForValue().get("stock");
        if (!StringUtils.hasText(stockValue)) {
            return "扣减库存失败,库存不足";
        }
        int stock = Integer.parseInt(stockValue);
        if (stock > 0) {
            reentrantLock.lock();
            try {
                stock--;
            } finally {
                reentrantLock.unlock();
            }
            stringRedisTemplate.opsForValue().set("stock", stock + "");
            log.info("扣减库存成功,库存stock:{}", stock);
        } else {
            log.info("扣减库存失败,库存不足");
        }
        return "end";
    }

    @RequestMapping("/set_stock")
    public String setStock() {
        stringRedisTemplate.opsForValue().set("stock", 10 + "");
        return "end";
    }
}
